package org.soenea.doitall.domain.model.group.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import org.dsrg.soenea.domain.MapperException;
import org.dsrg.soenea.domain.mapper.DomainObjectNotFoundException;
import org.dsrg.soenea.domain.mapper.IdentityMap;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.model.group.data.*;
import org.soenea.doitall.domain.model.group.*;
import org.soenea.doitall.domain.model.invite.InviteListProxy;

public class GroupInputMapper {

	public static Group find(long id) throws MapperException,
	DomainObjectNotFoundException {
		try {
			if (IdentityMap.has(id, Group.class))
				return IdentityMap.get(id, Group.class);
			
			ResultSet rs = GroupFinder.find(id);
			if (rs.next()) {
				return getGroup(rs);
			} else {
				throw new DomainObjectNotFoundException("Group " + id);
			}
		} catch (SQLException e) {
			throw new MapperException(e);
		}
	}

	public static List<Group> findAll() throws MapperException {
		List<Group> groups = new Vector<Group>();
		try {
			ResultSet rs = GroupFinder.findAll();
			while (rs.next()) {
				groups.add(getGroup(rs));
			}
		} catch (SQLException e) {
			throw new MapperException(e);
		}
		return groups;
	}

	private static Group getGroup(ResultSet rs) throws SQLException {
		IGroup grpRef = new GroupProxy(rs.getLong("g.groupID"));  
		Group result = new Group(rs.getLong("g.groupID"),rs.getString("g.groupName"),rs.getString("g.description"), rs.getLong("g.version"), new InviteListProxy(grpRef));
		UoW.getCurrent().registerClean(result);
		return result;
	}
}


